package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserLoginMapper;
import com.sky.result.Result;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserLoginMapper userLoginMapper;
    @Autowired
    private WorkspaceService workspaceService;
    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result<TurnoverReportVO> turnoverStatistics(LocalDate begin, LocalDate end) {
        //1.获取每日日期列表
        List<LocalDate> localDateList = new ArrayList<>();

        localDateList.add(begin);
        while (!begin.equals(end)){
           begin = begin.plusDays(1);//日期加一
           localDateList.add(begin);
        }

        //2.获取每日营业额列表
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate localDate : localDateList) {
            //获取每日的最大值和最小值
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap<>();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            turnover = turnover==null?0.0:turnover;
            turnoverList.add(turnover);
        }

        //3.封装数据
        // 3.1转换为字符串
        String dateListDtr = StringUtils.join(localDateList, ",");
        String turnoverListStr = StringUtils.join(turnoverList, ",");
        TurnoverReportVO vo = TurnoverReportVO.builder()
                .turnoverList(turnoverListStr)
                .dateList(dateListDtr).build();
        return Result.success(vo);
    }

    /**
     * 用户量统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result<UserReportVO> userStatistics(LocalDate begin, LocalDate end) {
        //1.获取日期集合
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //2.查询当天的所有用户数量
        List<Integer> totalList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            //查询当天的所有用户 (创建时间小于等于今天)
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MAX);

            Map map = new HashMap();
            map.put("end",beginTime);
            Integer  total =  userLoginMapper.countByMap(map);
            totalList.add(total);
        }

        //3.查询当日新增用户（创建时间等于今天
        List<Integer> newList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            //获取每日的最大值和最小值
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            //查询当天的新增用户 (创建时间小于等于今天)
            Map map = new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            Integer  total =  userLoginMapper.countByMap(map);
            newList.add(total);
        }


        //4.转换为字符串
        String dateListStr = StringUtils.join(dateList, ",");
        String totalListStr = StringUtils.join(totalList, ",");
        String newListStr = StringUtils.join(newList, ",");
        UserReportVO vo = UserReportVO.builder()
                .dateList(dateListStr)
                .newUserList(newListStr)
                .totalUserList(totalListStr).build();
        return Result.success(vo);
    }


    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result<OrderReportVO> ordersStatistics(LocalDate begin, LocalDate end) {


        //2.获取范围日期的订单总数
        // 2.1取范围日期的最大值最小值
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        Map map = new HashMap();
        map.put("begin",beginTime);
        map.put("end",endTime);
        //获取范围日期的订单总数
        Integer orderCount = orderMapper.countByMap(map);

        //3.获取范围日期的有效订单总数
        map.put("begin",beginTime);
        map.put("end",endTime);
        map.put("status",Orders.COMPLETED);
        //获取范围日期的有效订单总数
        Integer validOrder = orderMapper.countByMap(map);

        Double orderCompletionRate = 0.0;
        //4.订单完成率
        if (validOrder!=0){
            orderCompletionRate = validOrder.doubleValue()/orderCount.doubleValue();
        }

        //1.获取日期列表
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //5.获取每日订单数据
        List<Integer> todayOrdersList = new ArrayList<>();
        List<Integer> validOrderList = new ArrayList<>();
        for (LocalDate localDate : dateList) {
            //5.1 获取每日订单总数
            //获取每日的最大值最小值
             beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
             endTime = LocalDateTime.of(localDate, LocalTime.MAX);
             map = new HashMap();
             map.put("begin",beginTime);
             map.put("end",endTime);
             map.put("status",null);
            //获取当日的订单总数
            Integer todayCount = orderMapper.countByMap(map);
            todayOrdersList.add(todayCount);
            //5.2 获取每日有效订单
            map.put("status",Orders.COMPLETED);
            Integer todayValidCount = orderMapper.countByMap(map);
            validOrderList.add(todayValidCount);
        }

        String todayOrdersListStr = StringUtils.join(todayOrdersList, ",");
        String validOrderListSr = StringUtils.join(validOrderList, ",");
        String dateListStr = StringUtils.join(dateList, ",");
        OrderReportVO vo = OrderReportVO.builder()
                .totalOrderCount(orderCount)//订单总数
                .validOrderCount(validOrder)//有效订单总数
                .validOrderCountList(validOrderListSr)//每日有效订单
                .orderCountList(todayOrdersListStr)//每日订单
                .orderCompletionRate(orderCompletionRate)//订单完成率
                .dateList(dateListStr)//日期
                .build();
        return Result.success(vo);
    }

    /**
     * Top10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result<SalesTop10ReportVO> top10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.top10(beginTime,endTime);
        //把名字收集起来
        List<String> nameList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        //把销量收集起来
        List<Integer> numberList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        //转换成逗号分隔
        String nameListStr = StringUtils.join(nameList, ",");
        String numberListStr = StringUtils.join(numberList, ",");

        SalesTop10ReportVO vo = SalesTop10ReportVO.builder()
                .nameList(nameListStr)
                .numberList(numberListStr)
                .build();
        return Result.success(vo);
    }

    /**
     * 导出数据报表
     * @param response
     * @throws IOException
     */
    @Override
    public void export(HttpServletResponse response) {
        try {
            //1. 获取Excel模板文件的输入流
            InputStream in = this.getClass().getClassLoader().getResourceAsStream("运营数据模板.xlsx");

            //2. 创建Excel文件对象
            XSSFWorkbook workbook = new XSSFWorkbook(in);
            XSSFSheet sheet = workbook.getSheetAt(0);

            //3. 获取30天以前的日期
            LocalDate begin = LocalDate.now().minusDays(30);
            //3.1 30天以前的日期的0点0分0秒
            LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);

            //4. 获取昨天的日期
            LocalDate end = LocalDate.now().minusDays(1);
            //4.1 昨天的结束时间
            LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

            //5. 获取时间范围单元格子对象
            XSSFCell cellDate = sheet.getRow(1).getCell(1);

            //6. 设置时间范围单元格子的值
            cellDate.setCellValue("时间："+begin+"至"+end);

            //7. 查询最近30天的概览数据
            BusinessDataVO businessData = workspaceService.getBusinessData(beginTime, endTime);

            //8. 获取概览数据的每一项对应的单元格子对象并设置对应的值
            XSSFCell cell = sheet.getRow(3).getCell(2);
            if (cell==null){
                cell=sheet.getRow(3).createCell(2);
            }
            Double turnover = businessData.getTurnover();
            cell.setCellValue(turnover);
//            sheet.getRow(3).getCell(2).setCellValue(businessData.getTurnover());
            sheet.getRow(3).getCell(4).setCellValue(businessData.getOrderCompletionRate());
            sheet.getRow(3).getCell(6).setCellValue(businessData.getNewUsers());
            sheet.getRow(4).getCell(2).setCellValue(businessData.getValidOrderCount());
            sheet.getRow(4).getCell(4).setCellValue(businessData.getUnitPrice());

            //9. 遍历处理最近30天每一天的数据
            for (int i = 0; i < 30; i++) {
                //9.1 获取当天的日期
                LocalDate day = begin.plusDays(i);

                //9.2 获取当天日期开始时间点
                LocalDateTime dayBeginTime = LocalDateTime.of(day, LocalTime.MIN);

                //9.3 获取当天日期结束时间点
                LocalDateTime dayEndTime = LocalDateTime.of(day, LocalTime.MAX);

                //9.4 查询当天的运营数据
                BusinessDataVO dayDate = workspaceService.getBusinessData(dayBeginTime, dayEndTime);

                //9.5 获取当天对应的行对象的每个单元格子对象并设置对应的值
                XSSFRow row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(day.toString()); //日期
                row.getCell(2).setCellValue(dayDate.getTurnover());//营业额
                row.getCell(3).setCellValue(dayDate.getValidOrderCount());//有效订单
                row.getCell(4).setCellValue(dayDate.getOrderCompletionRate());//订单完成率
                row.getCell(5).setCellValue(dayDate.getUnitPrice());//平均客单价
                row.getCell(6).setCellValue(dayDate.getNewUsers());//新增用户数
            }
            //10 获取输入流
            ServletOutputStream out = response.getOutputStream();
            //11. 将excel写入response对象
            workbook.write(out);

            //12.释放流
            out.flush();
            out.close();
            workbook.close();
        } catch (IOException  e) {
            e.printStackTrace();
        }

    }
}
